﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using HZ.Model;
using HZ.Supervise.Model;
using System.Collections.Generic;

namespace HZ.Supervise.Web.Secondphase.ReportHospital
{
    public partial class CheckHospitalAmount : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //应补助金额
                txtHosPSubsidiesAmount.Text = Request.QueryString["PSubsidiesAmount"].ToString();
                //已补助金额
                txtHosPSbsidyAmount.Text = Request.QueryString["PSbsidyAmount"].ToString();
                txtProName.Text = Request.QueryString["text"].ToString();
            }
           
                      
        }

        protected void btnFinish_Click(object sender, EventArgs e)
        {
            HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
            IList<Prescription> prescriptionList = new List<Prescription>();
            Subsidy subsidy = new Subsidy();
            string strwhere1 = "";
            string  strstartime = "";
            string id=Request.QueryString["id"].ToString();
            string[] PrescriptionIds = id.Split(',');
                string PrescriptionId1 = "";
                for (int i = 0; i < PrescriptionIds.Length; i++)
                {
                    if (!PrescriptionIds[i].Equals(""))
                    {
                        PrescriptionId1 += "'" + PrescriptionIds[i] + "',";
                    }
                  
                }

                string strwhere = "and a.PrescriptionId in(" + PrescriptionId1.TrimEnd(',') + ")";
                strwhere1 += "and PrescriptionId in (" + PrescriptionId1.TrimEnd(',') + ")";
         
            string strPrice = TextBox2.Text;
            if (string.IsNullOrEmpty(strPrice))
            {
               Response.Write("<script>alert('补贴金额不能为空！')</script>");
               return;
            }
            StringBuilder sb = new StringBuilder();
            string SubsidyID = Guid.NewGuid().ToString();
            decimal price = Convert.ToDecimal(strPrice);
           decimal PSubsidiesAmount=   Convert.ToDecimal(Request.QueryString["PSubsidiesAmount"].ToString());
           decimal PSbsidyAmount=  Convert.ToDecimal(Request.QueryString["PSbsidyAmount"].ToString());
           if (price > PSubsidiesAmount - PSbsidyAmount)
           {
               Response.Write("<script>alert('补贴金额不能大于应补贴金额！')</script>");
               return;
           }
            string userid = CurrentAccount.GetUser().UserID;
            int size=0;
            DataTable dt = iPrescription.GetHospitalePrescrioDetail2(strwhere, 0, 1, out size);

             string strhospitname = dt.Rows[0]["PHospitalName"].ToString();
             string strhospitalid = dt.Rows[0]["PHospitalId"].ToString();
            string strareid = dt.Rows[0]["PAreaId"].ToString();
            string strarename = dt.Rows[0]["PAreaname"].ToString();
            string strendtime = DateTime.Now.ToString();
            string strPEssentialDrugsAmount = Request.QueryString["PEssentialDrugsAmount"].ToString();
            string strbz = txtBZ.Text;
            string strPSubsidiesAmount = txtHosPSubsidiesAmount.Text;
            string title = "";

            if (!txtProName.Text.Trim().Equals(""))
            {
                title = txtProName.Text.Trim();
            }
            else
            {
                title = CurrentAccount.GetUser().UserName + DateTime.Now.ToString("yyyyMMddHHmmss") + "结算单";
            }
            DataTable dt2 = iPrescription.GetHospitaleTB_Prescription(strwhere1);
            if (!strPrice.Equals(""))//是否空
            {
                if (dt2.Rows.Count > 0)
                {
                    if (string.IsNullOrEmpty(strstartime))
                    {
                        strstartime = dt2.Rows[0]["PSubmitTime"].ToString();
                    }
                   
                    //id
                    subsidy.SubsidyID = SubsidyID;
                    //地区Id
                    subsidy.Sareaid = Convert.ToInt32(strareid);
                    //地区名称
                    subsidy.Sareaname = strarename;
                    //医院Id
                    subsidy.SHospitalID = strhospitalid;
                    //医院名称
                    subsidy.SHospitalName = strhospitname;
                    //总金额
                    subsidy.SsumAmount = Convert.ToDecimal(strPEssentialDrugsAmount);
                    //已补贴总金额
                    subsidy.SubsidyAmount = Convert.ToDecimal(strPrice);
                    //补贴添加时间
                    subsidy.Saddtime = DateTime.Now;
                    //补贴人
                    subsidy.Sadduserid = userid;
                    //处方单开始时间
                    subsidy.SubsidyStartTime = Convert.ToDateTime(strstartime);
                    //处方单结束时间
                    subsidy.SubsidyEndTime = Convert.ToDateTime(strendtime);
                    //备注信息
                    subsidy.Remark = strbz;
                    //状态
                    subsidy.State = 0;
                    //结算单名称
                    subsidy.SubsidyName = title;
                    //应补贴金额
                    subsidy.Amount = Convert.ToDecimal(strPSubsidiesAmount);
                    sb.Append("insert tb_Subsidy  (SubsidyID, Sareaid, Sareaname, SHospitalID, SHospitalName,SsumAmount,  SubsidyAmount, Saddtime, Sadduserid, SubsidyStartTime, SubsidyEndTime, Remark, State,SubsidyName,Amount)     select   '" + SubsidyID + "','" + strareid + "','" + strarename + "','" + strhospitalid + "','" + strhospitname + "','" + strPEssentialDrugsAmount + "','" + strPrice + "',getdate(),'" + userid + "','" + strstartime + "','" + strendtime + "','" + strbz + "','0','" + title + "','" + strPSubsidiesAmount + "' ");
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        Prescription prescription = new Prescription();
                        //处方单中应补助金额
                        decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[i]["PSubsidiesAmount"].ToString());
                        //处方单中的已补助金额
                        decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[i]["PSbsidyAmount"].ToString());
                        //判断处方单中是否有已补助金额
                        if (prePSbsidyAmount > 0)
                        {
                            //算出未补贴金额
                            decimal UnPSbsidyAmount = prePSubsidiesAmount - prePSbsidyAmount;
                            //若未补助金额大于补贴金额
                            if (UnPSbsidyAmount > price)
                            {
                                prescription.POrderStatus = 2;
                                //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                prescription.PSbsidyAmount = prePSbsidyAmount + (UnPSbsidyAmount - price);
                                prescription.PSubmitTime = DateTime.Now;
                                prescription.PSubsidyUserid = userid;
                                prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                prescriptionList.Add(prescription);
                                price = 0;
                                break;
                            }
                            else
                            {
                                prescription.POrderStatus = 2;
                                //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                prescription.PSbsidyAmount =  prePSubsidiesAmount;
                                prescription.PSubmitTime = DateTime.Now;
                                prescription.PSubsidyUserid = userid;
                                prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                prescriptionList.Add(prescription);
                                //更新处方单表并把处方单中
                                price = price - UnPSbsidyAmount;
                            }

                        }

                    }
                    if (price > 0)
                    {
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            Prescription prescription = new Prescription();
                            //处方单中应补助金额
                            decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[j]["PSubsidiesAmount"].ToString());
                            //处方单中的已补助金额
                            decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[j]["PSbsidyAmount"].ToString());
                            //添加以补助金额为0的数据
                            if (prePSbsidyAmount <= 0)
                            {

                                //处方单应补助金额大于补助金额
                                if (prePSubsidiesAmount > price)
                                {
                                    prescription.POrderStatus = 2;
                                    //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                    prescription.PSbsidyAmount = prePSbsidyAmount + price;
                                    prescription.PSubmitTime = DateTime.Now;
                                    prescription.PSubsidyUserid = userid;
                                    prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                    prescriptionList.Add(prescription);
                                    string gu = Guid.NewGuid().ToString();
                                    //更新处方单表
                                    price = 0;
                                    break;
                                }
                                else
                                {
                                    prescription.POrderStatus = 2;
                                    //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                    prescription.PSbsidyAmount =prePSubsidiesAmount;
                                    prescription.PSubmitTime = DateTime.Now;
                                    prescription.PSubsidyUserid = userid;
                                    prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                    prescriptionList.Add(prescription);
                                    string gu = Guid.NewGuid().ToString();
                                    
                                    price = price - prePSubsidiesAmount;
                                }
                            }
                        }
                    }
                }
                else 
                {
                    Response.Write("<script>alert('医院已撤单！')</script>");
                    return;
                }
            }
            else
            {
                Response.Write("<script>alert('请填写补助金额！')</script>");
                return;
            }

            int nresult = iPrescription.UpdateAll(subsidy,prescriptionList,0);
            if (nresult > 0)
            {
              
                Response.Write("<script>alert('补贴发放成功！')</script>");
               // Response.Write("<script>location.href =hospitalPending.aspx;</script>");
                Page.RegisterClientScriptBlock("", "<script>addurl('hospitalPending.aspx')</script>");
              //  Response.Redirect("hospitalPending.aspx", false);
                
            }
            else
            {
                Response.Write("<script>alert('补贴发放失败！')</script>");
            }
            //if (nresult>0)
            //{

            //    Response.Redirect("hospitalPending.aspx", false);
            //}
        }

        protected void btnFinish0_Click(object sender, EventArgs e)
        {
            string PHospitalId = Request.QueryString["PHospitalId"].ToString();
            string PEssentialDrugsAmount = Request.QueryString["PEssentialDrugsAmount"].ToString();
            string PAreaId = Request.QueryString["PAreaId"].ToString();
            Response.Redirect(string.Format("hospitalAmountSubsidyDetailUn.aspx?id=0&PEssentialDrugsAmount=" + PEssentialDrugsAmount + "&PAreaId=" + PAreaId + "&PHospitalId=" + PHospitalId), true);
        }
    }
}
